package cn.jroid.demo.ui;

import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ListView;
import cn.jroid.demo.R;
import cn.jroid.demo.adapter.ImageListAdapter;
import cn.jroid.demo.entity.Image;

public class ImageListActivity extends Activity {
	
	private ListView imageList;
	private Button postBtn;
	
	/*
	 * 变量声明
	 * newName：上传后在服务器上的文件名称 
	 * uploadFile：要上传的文件路径
	 * actionUrl：服务器对应的程序路径
	 */
	private String newName = "";
	private String uploadFile = "";
	private String actionUrl = "http://10.0.2.2/jroid_frame_server/upload.php";

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.image_list);
		
		imageList = (ListView)findViewById(R.id.image_list);
		postBtn = (Button) findViewById(R.id.postBtn);
		
		List<Image> images = new ArrayList<Image>();
		
		Image img0 = new Image("http://photos.tuchong.com/19105/f/600331.jpg","测试图片标题");
		Image img1 = new Image("http://www.baidu.com/img/baidu_logo.gif","测试图片标题");
		Image img2 = new Image("http://www.chinatelecom.com.cn/images/logo_new.gif","测试图片标题");
		Image img3 = new Image("http://cache.soso.com/30d/img/web/logo.gif","测试图片标题");
		Image img4 = new Image("http://csdnimg.cn/www/images/csdnindex_logo.gif","测试图片标题");
		Image img5 = new Image("http://csdnimg.cn/www/images/csdnindex_logo.gif","测试图片标题");
		Image img6 = new Image("http://csdnimg.cn/www/images/csdnindex_logo.gif","测试图片标题");
		Image img7 = new Image("http://csdnimg.cn/www/images/csdnindex_logo.gif","测试图片标题");
		Image img8 = new Image("http://csdnimg.cn/www/images/csdnindex_logo.gif","测试图片标题");
		
		images.add(img0);
		images.add(img1);
		images.add(img2);
		images.add(img3);
		images.add(img4);
		images.add(img5);
		images.add(img6);
		images.add(img7);
		images.add(img8);
		
		
		ImageListAdapter adapter = new ImageListAdapter(this, images, imageList);
		
		imageList.setAdapter(adapter);
		
		//Intent intent = this.getIntent();
		//Bundle bundle = intent.getExtras();
		//newName = bundle.getString("fileName");
		newName = "/sdcard/zdry.JPG";
		uploadFile = newName;
		
		postBtn.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				// TODO Auto-generated method stub
				new Thread(PostThread).start();
			}
		});
		
	}
	
	Runnable PostThread = new Runnable() {

		@Override
		public void run() {
			// TODO Auto-generated method stub
			try {
				String ok = post(actionUrl, newName);
				System.out.println(ok);
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
	};
	
	/* 上传文件到Server的方法 */
	/**
	 * 
	 * @param actionUrl
	 * @param params
	 * @param files
	 * @return
	 * @throws IOException
	 */
	public String post(String actionUrl, String FileName)
			throws IOException {

		String BOUNDARY = java.util.UUID.randomUUID().toString();
		String PREFIX = "--", LINEND = "\r\n";
		String MULTIPART_FROM_DATA = "multipart/form-data";
		String CHARSET = "UTF-8";

		URL uri = new URL(actionUrl);
		HttpURLConnection conn = (HttpURLConnection) uri.openConnection();
		conn.setReadTimeout(5 * 1000); // 缓存的最长时间
		conn.setDoInput(true);// 允许输入
		conn.setDoOutput(true);// 允许输出
		conn.setUseCaches(false); // 不允许使用缓存
		conn.setRequestMethod("POST");
		conn.setRequestProperty("connection", "keep-alive");
		conn.setRequestProperty("Charsert", "UTF-8");
		conn.setRequestProperty("Content-Type", MULTIPART_FROM_DATA
				+ ";boundary=" + BOUNDARY);

		DataOutputStream outStream = new DataOutputStream(
				conn.getOutputStream());

		// 发送文件数据
		if (FileName != "") {

			StringBuilder sb1 = new StringBuilder();
			sb1.append(PREFIX);
			sb1.append(BOUNDARY);
			sb1.append(LINEND);
			sb1.append("Content-Disposition: form-data; name=\"file1\"; filename=\""
					+ FileName + "\"" + LINEND);
			sb1.append("Content-Type: application/octet-stream; charset="
					+ CHARSET + LINEND);
			sb1.append(LINEND);
			outStream.write(sb1.toString().getBytes());

			InputStream is = new FileInputStream(FileName);
			byte[] buffer = new byte[1024];
			int len = 0;
			while ((len = is.read(buffer)) != -1) {
				outStream.write(buffer, 0, len);
			}

			is.close();
			outStream.write(LINEND.getBytes());

		}

		// 请求结束标志
		byte[] end_data = (PREFIX + BOUNDARY + PREFIX + LINEND).getBytes();
		outStream.write(end_data);
		outStream.flush();

		// 得到响应码
		int res = conn.getResponseCode();
		InputStream in = null;
		if (res == 200) {
			in = conn.getInputStream();
			int ch;
			StringBuilder sb2 = new StringBuilder();
			while ((ch = in.read()) != -1) {
				sb2.append((char) ch);
			}
			showDialog("上传成功"+sb2.toString().trim());
		}
		return in == null ? null : in.toString();
	}
	
	/* 显示Dialog的method */
	private void showDialog(String mess) {
		new AlertDialog.Builder(ImageListActivity.this).setTitle("Message")
				.setMessage(mess)
				.setNegativeButton("确定", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int which) {
					}
				}).show();
	}

}
